<template>
  <div>
    <!--引入批量删除的按钮-->
    <el-button type="danger" @click="batchDel" style="margin-bottom: 10px" size="small">批量删除</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      show-checkbox
      node-key="id"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      ref="categoryTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)">
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            编辑
          </el-button>
          <el-button
            v-if="node.childNodes.length === 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>

    </el-tree>
    <!--引入对话框-->
    <el-dialog title="添加/修改分类" :visible.sync="dialogVisible">
      <el-form :model="categoryForm">
        <el-form-item label="分类名">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="categoryForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="统计单位">
          <el-input v-model="categoryForm.proUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click=addOrUpdate>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data () {
    return {
      data: [],
      expandedKey: [],
      defaultProps: {
        children: 'childrenCategories',
        label: 'name'
      },
      dialogVisible: false,
      // 标识对话框类别
      dialogType: '',
      categoryForm: {
        id: null,
        name: '',
        parentId: 0,
        catLevel: 0,
        isShow: 1,
        sort: 0,
        icon: '',
        proUnit: '',
        proCount: 0
      }
    }
  },
  methods: {
    batchDel () {
      const checkedNodes = this.$refs.categoryTree.getCheckedNodes()
      const ids = []
      const categoryNames = []
      checkedNodes.forEach(node => {
        ids.push(node.id)
        categoryNames.push(node.name)
      })

      this.$confirm(`确定对【${categoryNames}】执行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/commodity/category/delete'),
          // url: 'http://localhost:9090/commodity/category/delete',
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '批量删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    addOrUpdate () {
      if (this.dialogType === 'edit') {
        this.updateCategory()
      }
      if (this.dialogType === 'add') {
        this.addCategory()
      }
    },
    // 添加分类
    append (data) {
      this.categoryForm.name = ''
      this.categoryForm.icon = ''
      this.categoryForm.proUnit = ''
      this.dialogType = 'add'
      this.dialogVisible = true
      this.categoryForm.parentId = data.id
      this.categoryForm.sort = 0
      // 注意：将 catLevel * 1 是为了将字符串转化为数值
      this.categoryForm.catLevel = data.catLevel * 1 + 1
    },
    // 删除分类
    remove (node, data) {
      const ids = [data.id]
      this.$confirm(`确定对【${data.name}】执行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/commodity/category/delete'),
          // url: 'http://localhost:9090/commodity/category/delete',
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
                console.log('add id = ' + node.parent.data.id)
                this.expandedKey = [node.parent.data.id]
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 编辑分类
    edit (data) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/commodity/category/info/${data.id}`),
        // url: `http://localhost:9090/commodity/category/info/${data.id}`,
        method: 'get'
      }).then(({data}) => {
        this.categoryForm.parentId = data.category.parentId
        this.categoryForm.name = data.category.name
        this.categoryForm.icon = data.category.icon
        this.categoryForm.proUnit = data.category.proUnit
        this.categoryForm.id = data.category.id
      })
    },
    getDataList () {
      this.$http({
        url: this.$http.adornUrl('/commodity/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.data = data.data
        }
      })
    },
    addCategory () {
      this.$http({
        url: this.$http.adornUrl('/commodity/category/save'),
        method: 'post',
        data: this.$http.adornData(this.categoryForm, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '分类信息保存成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.dialogVisible = false
              this.getDataList()
              this.expandedKey = [this.categoryForm.parentId]
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    updateCategory () {
      // 这里我们只需提交要修改的字段信息
      const {id, name, icon, proUnit} = this.categoryForm
      this.$http({
        url: this.$http.adornUrl('/commodity/category/update'),
        method: 'post',
        data: this.$http.adornData({id, name, icon, proUnit})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '商品分类修改成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.dialogVisible = false
              this.getDataList()
              console.log(this.categoryForm.parentId)
              this.expandedKey = [this.categoryForm.parentId]
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    }
  },
  created () {
    this.getDataList()
  }
}
</script>
